package model

import (
	"time"
	"user_srv/basic/config"
)

// 用户灵魂档案表
type XqUserSoulProfile struct {
	Id                   int64     `gorm:"column:id;type:bigint(20);comment:档案ID;primaryKey;not null;" json:"id"`
	UserId               int64     `gorm:"column:user_id;type:bigint(20);comment:用户ID;not null;" json:"user_id"`
	PersonalityType      string    `gorm:"column:personality_type;type:varchar(50);comment:性格类型;" json:"personality_type"`
	PersonalityTraits    string    `gorm:"column:personality_traits;type:json;comment:性格特征(JSON);" json:"personality_traits"`
	LifestylePreferences string    `gorm:"column:lifestyle_preferences;type:json;comment:生活方式偏好(JSON);" json:"lifestyle_preferences"`
	CoreValues           string    `gorm:"column:core_values;type:json;comment:核心价值观(JSON);" json:"core_values"`
	RelationshipStyle    string    `gorm:"column:relationship_style;type:varchar(50);comment:恋爱风格;" json:"relationship_style"`
	CompletionRate       float64   `gorm:"column:completion_rate;type:decimal(5,2);comment:答题完成率;default:0.00;" json:"completion_rate"`
	LastAnsweredAt       time.Time `gorm:"column:last_answered_at;type:timestamp;comment:最后答题时间;" json:"last_answered_at"`
	CreatedAt            time.Time `gorm:"column:created_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;" json:"created_at"`
	UpdatedAt            time.Time `gorm:"column:updated_at;type:timestamp;not null;default:CURRENT_TIMESTAMP;" json:"updated_at"`
}

func (x *XqUserSoulProfile) TableName() string {
	return "xq_user_soul_profile"
}

func (x *XqUserSoulProfile) Create() error {
	return config.DB.Create(&x).Error
}

func (x *XqUserSoulProfile) Delete(where XqUserSoulProfile) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqUserSoulProfile) Update(where XqUserSoulProfile) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqUserSoulProfile) GetByUserId(userId int64) (*XqUserSoulProfile, error) {
	var profile XqUserSoulProfile
	err := config.DB.Where("user_id = ?", userId).First(&profile).Error
	return &profile, err
}

func (x *XqUserSoulProfile) CreateOrUpdate(profile XqUserSoulProfile) error {
	var existing XqUserSoulProfile
	err := config.DB.Where("user_id = ?", profile.UserId).First(&existing).Error
	if err != nil {
		// 不存在，创建新记录
		return config.DB.Create(&profile).Error
	} else {
		// 存在，更新记录
		profile.Id = existing.Id
		return config.DB.Save(&profile).Error
	}
}
